﻿using NLog;
using Scap.Data;
using Scap.Info;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace Scap.Core
{
    class SchedulerHandler
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();



        internal void Run()
        {
            logger.Info("Inicializando scheduler...");
            Timer t = new Timer();
            t.Interval = 5000; // SYSTEM INTERVAL
            t.Enabled = true;
            t.AutoReset = true;
            t.Elapsed += t_Elapsed;
            t.Start(); 
            logger.Info("Inicializando scheduler...[OK]");
        }

        int initialSecs = (int)Math.Round(DateTime.Now.TimeOfDay.TotalSeconds);

        void t_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                logger.Trace("Ejecutando scheduler...");

                ConfigurationHandler configHandler = new ConfigurationHandler();
                int interval = configHandler.GetMonitorInterval();//60; // default , pending read from db

                int cuurentSecs = (int) Math.Round(DateTime.Now.TimeOfDay.TotalSeconds);
                int targetSecs = initialSecs + interval;

                if (cuurentSecs > targetSecs)
                {
                    initialSecs = cuurentSecs;
                    DeviceMonitor monitor = new DeviceMonitor();
                    monitor.Launch();                 
                }

                logger.Trace("Ejecutando scheduler...[OK]");
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
    }
}
